CREATE VIEW service_meta_foreign_keys AS
WITH
    tables AS (
        SELECT tbl_name AS table_name, sql
        FROM sqlite_master
        WHERE type = 'table'
          AND name NOT LIKE 'sqlite_%'
    ),
    fkey_columns AS (
        SELECT table_name AS src_table, "from" AS src_col,
               "table" AS dst_table, "to" AS dst_col,
               on_update, on_delete, id AS fk_id, seq AS fk_seq
        FROM tables AS t,
             pragma_foreign_key_list (t.table_name)
        ORDER BY src_table, fk_id, fk_seq
    ),
    foreign_keys AS (
        SELECT src_table, json_group_array(src_col) AS src_cols,
               dst_table, json_group_array(dst_col) AS dst_cols,
               on_update, on_delete, fk_id
        FROM fkey_columns
        GROUP BY src_table, fk_id
        ORDER BY src_table, dst_table
    )
SELECT * FROM foreign_keys;